package com.zyao89.view.zweb.views;

import com.zyao89.view.zweb.ZWebConfig;
import com.zyao89.view.zweb.utils.ZLog;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.webengine.*;
import ohos.app.Context;
import ohos.media.image.PixelMap;
import ohos.net.http.SslError;
import ohos.utils.net.Uri;

/**
 * @author Zyao89
 * 2017/11/13.
 */
public class ZWebView implements IZWebView {
    private final Context mContext;

    private WebViewEx mWebView;

    private OnErrorListener mOnErrorListener;
    private OnPageListener mOnPageListener;

    public ZWebView(Context context) {
        mContext = context;
    }

    public void setConfig(ZWebConfig config) {

    }

    @Override
    public Component getView() {
        if (mWebView == null) {
            mWebView = new WebViewEx(mContext);
            ComponentContainer.LayoutConfig wvLayoutParams = new ComponentContainer.LayoutConfig(
                    ComponentContainer.LayoutConfig.MATCH_PARENT,
                    ComponentContainer.LayoutConfig.MATCH_PARENT);
            mWebView.setLayoutConfig(wvLayoutParams);
            ShapeElement element1 = new ShapeElement();
            element1.setRgbColor(new RgbColor(0, 204, 255));
            mWebView.setBackground(element1);
            initWebView(mWebView);
        }
        return mWebView;
    }

    @Override
    public void onPause() {
        if (getWebView() == null) {
            return;
        }
        getWebView().onInactive();
    }

    @Override
    public void onResume() {
        if (getWebView() == null) {
            return;
        }
        getWebView().reload();
    }

    @Override
    public void destroy() {
        if (getWebView() != null) {
            getWebView().onStop();
            mWebView = null;
        }
    }

    @Override
    public void loadUrl(String url) {
        if (getWebView() == null) {
            return;
        }
        getWebView().load(url);
    }

    @Override
    public void evaluateJavascript(String script) {
        if (getWebView() == null) {
            return;
        }

        getWebView().executeJs(script, null);
    }

    @Override
    public void reload() {
        if (getWebView() == null) {
            return;
        }
        getWebView().reload();
    }

    @Override
    public boolean canGoBack() {
        if (getWebView() == null) {
            return false;
        }
//        return getWebView().canGoBack();
        return getWebView().getNavigator().canGoBack();
    }

    @Override
    public void goBack() {
        if (getWebView() == null) {
            return;
        }
        getWebView().getNavigator().goBack();
    }

    @Override
    public void goForward() {
        if (getWebView() == null) {
            return;
        }
        getWebView().getNavigator().goForward();
    }

    @Override
    public void addJavascriptInterface(Object object, String name) {
        if (getWebView() == null) {
            return;
        }
        ((WebViewEx) getWebView()).addJavascriptInterface(object, name);
    }

    @Override
    public void setOnErrorListener(OnErrorListener listener) {
        mOnErrorListener = listener;
    }

    @Override
    public void setOnPageListener(OnPageListener listener) {
        mOnPageListener = listener;
    }

    private void showWebView(boolean shown) {
        mWebView.setVisibility(shown ? Component.VISIBLE : Component.INVISIBLE);
    }

    private WebView getWebView() {
        //TODO: remove this, duplicate with getView semantically.
        return mWebView;
    }

    private void initWebView(WebViewEx wv) {
        WebConfig settings = wv.getWebConfig();
        // 设置是否启用HTML5 DOM存储。
        settings.setJavaScriptPermit(true);
        settings.setWebStoragePermit(true);
        // 表示WebView将允许安全源从其他源（甚至是来自不安全源）加载内容。
        settings.setSecurityMode(WebConfig.SECURITY_ALLOW);
        settings.setLoadsImagesPermit(true);
        settings.setViewPortFitScreen(true);
        settings.setTextAutoSizing(true);

        wv.setBrowserAgent(new BrowserAgentEx(wv.getContext()) {
            @Override
            public void onProgressUpdated(WebView webView, int newValue) {
                super.onProgressUpdated(webView, newValue);
            }

            @Override
            public void onTitleUpdated(WebView webView, String value) {
                super.onTitleUpdated(webView, value);
            }
        });

        wv.setWebAgent(new WebAgentEx() {

            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                Uri uri = request.getRequestUrl();
                ZLog.with(this).z("onPageOverride " + uri);
                return super.isNeedLoadUrl(webView, request);
            }

            @Override
            public void onLoadingPage(WebView webView, String url, PixelMap icon) {
                super.onLoadingPage(webView, url, icon);
                ZLog.with(this).z("onPageStarted " + url);
                if (mOnPageListener != null) {
                    mOnPageListener.onPageStart(url);
                }
            }

            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);
                ZLog.with(this).z("onPageFinished " + url);
                if (mOnPageListener != null) {
                    mOnPageListener.onPageFinish(url, false, false);
                }
            }

            @Override
            public void onLoadingContent(WebView webView, String url) {
                ZLog.with(this).z("onLoadResource " + url);
                super.onLoadingContent(webView, url);
            }

            @Override
            public void onError(WebView webView, ResourceRequest request, ResourceError error) {
                super.onError(webView, request, error);
                if (mOnErrorListener != null) {
                    mOnErrorListener.onError("error", "page error");
                }
            }

            @Override
            public void onSslError(WebView webView, SslError error) {
                super.onSslError(webView, error);
                if (mOnErrorListener != null) {
                    mOnErrorListener.onError("error", "onSslError error");
                }
            }

            @Override
            public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
                return super.processResourceRequest(webView, request);
            }
        });
    }
}
